<?php
if( !defined('CORE') ) exit('Request Error!');

class mod_book
{
    //分类数组
    private static $type_arr = array();

    //标签数组
    private static $tag_arr = array();

    private static function init()
    {
        $res_type = db::get_all("SELECT * FROM `book_tag` WHERE `id` < 100");
        if($res_type) foreach ($res_type as $k=>$v)
        {
           self::$type_arr[$v['id']] = $v['name']."[{$v['id']}]";
        }

        $res_tag = db::get_all("SELECT * FROM `book_tag` WHERE `id` > 100");
        if ($res_tag) foreach ($res_tag as $k1 => $v1)
        {
            self::$tag_arr[$v1['id']] = $v1['name'];
        }
    }

    //书籍首页
    public static function index()
    {  
        self::init();
        // 获取
        $id = req::item("id",0);
        //$start_date = req::item("start_iate", date('Y-m-d', time()-24*3600));
        //$end_date = req::item("end_date", date('Y-m-d', time()));
        $start_date = req::item("start_iate",'');
        $end_date = req::item("end_date",'');
        $book_id = req::item('book_id','');
        $book_name = req::item('book_name', '');
        $book_type = req::item('book_type', '');
        $book_suffix = req::item('book_suffix', '');
        $where = $url = array();

        // 条件
        if($id)
        {
            $where[] = "`id` ='$id'";
            $url['id'] = $id;
        }
        if($book_id)
        {
            $where[] = "`book_id` ='$book_id'";
            $url['book_id'] = $book_id;
        }
        if($book_name)
        {
            $where[] = "`book_name` like'%{$book_name}%'";
            $url['book_name'] = $book_name;
        }
        if($book_suffix)
        {
            $where[] = "`book_suffix` ='$book_suffix'";
            $url['book_suffix'] = $book_suffix;
        }
        if ($start_date && $end_date) {
            $where[] = "`add_date` between '{$start_date}' and '{$end_date}'";
            $url['s_date'] = $start_date;
            $url['e_date'] = $end_date;
        }

        // 组装条件
        $where = empty($where) ? '' : 'WHERE ' . implode(' AND ', $where);
        $url = empty($url) ? '' : '&' . http_build_query($url);
        $order = "ORDER BY `id` DESC";

        // 获取page
        $current_page = req::item('page_no', 1);
        $page_size = 15;
        $offset = ($current_page - 1) * $page_size;

        // 高效分页sql
        $sql = "SELECT SQL_CALC_FOUND_ROWS* FROM `book` {$where} {$order} LIMIT {$offset}, {$page_size}";
        $list = db::get_all($sql);
        $row = db::get_one("SELECT FOUND_ROWS() AS rowscount");
        $rowscount = $row['rowscount'];

        // 分页
        $config['current_page'] = $current_page; // 当前页数,至少为1
        $config['page_size'] = $page_size; // 每页显示多少条
        $config['total_rs'] = $rowscount; // 总记录数
        $config['url_prefix'] =  '?ct='.req::item('ct').'&ac='.req::item('ac') . $url; // 网址前缀
        $config['page_name'] = 'page_no'; // 当前分页变量名(默认是page_no,即访问是用 url_prefix&page_no=xxx )
        $config['move_size'] = 5; // 前后偏移量（默认是5）
        $config['input'] = 0; // 是否使用输入跳转框(0|1)
        $pages = util::pagination($config);

        //处理数据
        if ($list)foreach ($list as $k => $v)
        {
            //$list[$k]['ajax_call_url'] = (in_array($v['caiji_is_call'],array(0,2)))? '?ct=book&ac=ajax_call_send&book_id='.$v['book_id']:'';
            //$list[$k]['ajax_down_url'] = (in_array($v['caiji_read_email_url'],array(0,2)))? $v['caiji_read_email_url']:'';

            //$lists[$k]['book_tag'] = explode("," ,$lists[$k]['book_tag']);
            //$tmp = "";
            //if ($lists[$k]['book_tag']) foreach ($lists[$k]['book_tag'] as $k1 => $v1)
            //{
            //    $tmp .= !empty(self::$tag_arr[$v1]) ? self::$tag_arr[$v1].'，' : "";
            //}
            //$lists[$k]['book_tag'] = rtrim($tmp , '，');
            //$lists[$k]['book_tag'] = mb_substr($lists[$k]['book_tag'],0,25,'utf-8').(strlen($lists[$k]['book_tag']) > 25 ? '...略' : '');
        }

        tpl::assign('list', $list);
        tpl::assign('pages', $pages);
        tpl::assign("start_date", $start_date);
        tpl::assign("end_date", $end_date);
        tpl::assign("book_id", $book_id);
        tpl::assign("book_name", $book_name);
        tpl::assign("book_suffix", $book_suffix);
        tpl::assign("id", $id);
        tpl::assign("type_arr", self::$type_arr);
        tpl::display("book.index.tpl");
    }

    public static function ajax_call_send()
    {
        $book_id = req::item("book_id",'0','int');
        $id = req::item("id");
        $res = array('errcode' => 1, 'msg' => '失败');

        $is_send = pub_mod_book_fun::call_send_email($book_id);
        if($is_send)
        {
            //db::update('book', array('is_call' => 1),'book_id='.$book_id);
            db::query("update book set caiji_is_call=caiji_is_call+1 where id='{$id}'");
            $res['errcode']=0;
            $res['msg']='成功请求对方发送email';
        }

        exit(json_encode($res));
    }

    // 读取邮件一般都是全部读取的，不存在读取单个
    public static function ajax_read_email()
    {
        $res = array('errcode' => 1, 'msg' => '失败');

        $is = pub_mod_book_fun::save_record_fordb(); 
        if($is)
        {
            $res['errcode']=0;
            $res['msg']='成功读取服务器邮件';
        }
        exit(json_encode($res));
    }

    // 接收一个下载链接，然后保存到服务器
    public static function ajax_down_book()
    {
        $id = req::item('id', '0', 'int');
        $res = array('errcode' => 1, 'msg' => '无相关下载链接');
        $bookinfo = db::get_all("select id,caiji_read_email_url,book_name from book WHERE id='{$id}' limit 1");
        if($bookinfo)
        {
            $d = pub_mod_book_fun::down_book_url($bookinfo);

            if($d) $res = array('errcode' => 0, 'msg' => '成功下载');
        }
        exit(json_encode(($res)));

    }

    //过滤POST
    public static function filter_post()
    {
        $book_name = req::item("book_name");
        if (empty($book_name))
        {
            cls_msgbox::show("书籍添加" , "书名不能为空" , -1);
        }

        $book_cat = req::item("book_type");
        if (empty($book_cat))
        {
            cls_msgbox::show("书籍添加" , "书分类不能为空" , -1);
        }

        $book_type = req::item("book_suffix");
        if (empty($book_type))
        {
            cls_msgbox::show("书籍添加" , "后缀名不能为空" , -1);
        }

        $down_url = req::item("down_url");
        if (empty($down_url))
        {
            cls_msgbox::show("书籍添加" , "网络链接不能为空" , -1);
        }
    }

    //书籍添加
    public static function add()
    {
        self::init();
        if (req::$posts)
        {
            self::filter_post();

            //生成路径
            $savepath = PATH_UPLOADS . "/book/".date('Y/m/');
            util::path_exists($savepath);

            //文件上传
            $option = array('upload_path'=>$savepath,
                'type_limit'=>array('jpg','png','bmp','gif','docx','txt','mobi'),
                'size_limit'=>3000000,
                'is_strict'=>'');
            $obj = new cls_upload($option);
            var_dump(req::$files);
            $savename = $obj->upload('file'); var_dump($savename);exit;
            $url = "/book/".date('Y/m/').iconv("gbk","utf-8",$savename);


            req::$posts['book_tag'] = implode("," , req::$posts['book_tag']);
            req::$posts['add_time'] = time();
            req::$posts['down_path'] = $arr;
            db::insert("book" , req::$posts);
            $row = db::affected_rows();
            if ($row > 0)
            {
                $gourl = empty($_SERVER['HTTP_REFERER']) ? '?ct=book&ac=index' : $_SERVER['HTTP_REFERER'];
                cls_msgbox::show("书籍添加", "添加成功", $gourl);
            }
        }

        tpl::assign("tag_arr",self::$tag_arr);
        tpl::assign("type_arr",self::$type_arr);
        $type_arr_ted = "";
        tpl::assign("type_arr_ted",$type_arr_ted);
        tpl::display("book.add.tpl");

    }

    //书籍修改
    public static function edit()
    {
        self::init();
        $id = req::item("id");
        if(req::$posts)
        {
            req::$posts['book_tag'] = implode(',', req::$posts['book_tag']);
            db::update("book" , req::$posts ,"`id` = '{$id}'");
            $gourl = empty($_SERVER['HTTP_REFERER']) ? '?ct=book&ac=index' : $_SERVER['HTTP_REFERER'];
            cls_msgbox::show("书籍修改" ,"修改成功" ,$gourl);
        }
        else
        {
            $sql = "SELECT * FROM `book` WHERE `id`='{$id}'";
            $list = db::get_one($sql);
            $list['book_tag'] = explode(',', $list['book_tag']);
        }

        tpl::assign("v",$list);
        tpl::assign("type_arr",self::$type_arr);
        tpl::assign("tag_arr",self::$tag_arr);
        tpl::display('book.edit.tpl');
    }

    //书籍删除
    public static function del()
    {
        $id = req::item("id");
        if(!empty($id))
        {
            db::query("DELETE FROM `book` WHERE `id` ='{$id}'");
            $gourl = empty($_SERVER['HTTP_REFERER']) ? '?ct=book&ac=index' : $_SERVER['HTTP_REFERER'];
            cls_msgbox::show("书籍删除" ,"删除成功" ,$gourl);
        }
    }

    //搜索书籍
    public static function search_list()
    {
        // 获取
        $book_id = req::item('book_id', '');
        $book_name = req::item('book_name', '');
        $submit = req::item('submit','');
        $alert = '';
        $list = array();

        if($book_name)
        {
            $rows_local = array();
            $local = db::get_all("select book_id,book_name from book where book_id>0 and book_name like '%{$book_name}%'");
            //var_dump($local);
            if($local)foreach($local as $k=>$v)
            {
                $rows_local[$v['book_id']] = array(
                    'title' =>$v['book_name'],
                    'url' =>'?ct=index&ac=receiv_choose&book_id='.$v['book_id'].'&title='.$v['book_name'],
                    'book_id' =>$v['book_id'],
                );
            }
            //var_dump($rows_local);
            //如果本地有的，就不显示网络上的书籍
            $rows = pub_mod_book_fun::get_ansy_search($book_name);
            $time = time();

            if(is_array($rows)) foreach($rows as $k=>$v)
            {
                $list[] = array(
                    'book_name' =>(!isset($rows_local[$v['id']]))? $v['title'] : $v['title'].'--------本地已存在',
                    'url' =>'?ct=index&ac=receiv_choose&book_id='.$v['id'].'&title='.$v['title'],
                    'book_id' =>$v['id'],
                );
                if (!isset($rows_local[$v['id']]) && $submit=='查询并保存')
                {
                    $title = str_replace(array('/',"\\",':','*','?','<','>','|',' '),'',$v['title']);
                    $suffix = pathinfo($title,PATHINFO_EXTENSION );                    

                    $e = db::get_one("select id from book where book_name='{$title}' limit 1");
                    if($e){
                        db::update('book',array('book_id'=>$v['id'],'book_suffix'=>$suffix),"id='{$e['id']}'");
                    }else{
                        db::query("INSERT INTO `book` (`book_id`,`book_name`,`book_suffix`) VALUES ('{$v['id']}','{$title}','{$suffix}')" );
                    }
                    
                    $db = db::affected_rows();
                    if ($db > 0)
                    {
                       $alert = "你采集的书籍 “书名” 和 “ID” 已入库";
                    }
                }
            }
        }
        tpl::assign('list', $list);
        tpl::assign("book_id", $book_id);
        tpl::assign("book_name", $book_name);
        tpl::assign("alert", $alert);
        tpl::display('search.list.tpl');
    }

    //
}
